package cs180battleships;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

import javax.swing.*;

import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.wb.swt.*;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI Builder, which is free for non-commercial use. If Jigloo is
 * being used commercially (ie, by a corporation, company or business for any purpose whatever) then you should purchase a license for each
 * developer using Jigloo. Please visit www.cloudgarden.com for details. Use of Jigloo implies acceptance of these licensing terms. A
 * COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR ANY CORPORATE OR COMMERCIAL
 * PURPOSE.
 */
public class MainWindow {

	protected Shell battleshipGameLauncherShell;
	private Text serverNameText;
	private Button joinServerBtn;
	private Button startserverbtn;
	Properties appSettings = new Properties();
	Cursor defaultCursor; // To change the cursor to an arrow at any point after
							// MainWindow() has executed, use
	// shell.setCursor(defaultCursor);
	Cursor waitCursor; // To change the cursor to an hourglass at any point
						// after MainWindow() has executed, use
	// shell.setCursor(waitCursor);
	private Composite clientArea;
	GameServer serverApplication;
	GameClient clientApplication;
	//BattleShipsClient clientApplication;
	private ExecutorService runServerClient;
	private ReentrantLock hostLock;
	public String serverMessage = "";
	boolean isServer=false;


	/**
	 * Launch the application.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			MainWindow window = new MainWindow();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();

		setPreferences();
		waitCursor = battleshipGameLauncherShell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT);
		defaultCursor = battleshipGameLauncherShell.getDisplay().getSystemCursor(SWT.CURSOR_ARROW);
		clientArea.setFocus();

		battleshipGameLauncherShell.open();
		battleshipGameLauncherShell.layout();
		while (!battleshipGameLauncherShell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}


	// Load application settings from .ini file
	private void setPreferences() {
		try {
			appSettings.load(new FileInputStream("appsettings.ini"));
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}

		// By default, center window
		int width = Integer.parseInt(appSettings.getProperty("width", "640"));
		int height = Integer.parseInt(appSettings.getProperty("height", "480"));
		Rectangle screenBounds = battleshipGameLauncherShell.getDisplay().getBounds();
		int defaultTop = (screenBounds.height - height) / 2;
		int defaultLeft = (screenBounds.width - width) / 2;
		int top = Integer.parseInt(appSettings.getProperty("top", String.valueOf(defaultTop)));
		int left = Integer.parseInt(appSettings.getProperty("left", String.valueOf(defaultLeft)));
		battleshipGameLauncherShell.setSize(width, height);
		battleshipGameLauncherShell.setLocation(left, top);
		saveShellBounds();
	}


	// Save window location in appSettings hash table
	private void saveShellBounds() {
		// Save window bounds in app settings
		Rectangle bounds = battleshipGameLauncherShell.getBounds();
		appSettings.setProperty("top", String.valueOf(bounds.y));
		appSettings.setProperty("left", String.valueOf(bounds.x));
		appSettings.setProperty("width", String.valueOf(bounds.width));
		appSettings.setProperty("height", String.valueOf(bounds.height));
	}


	/**
	 * Create contents of the window.
	 */
	protected void createContents() {

		runServerClient = Executors.newFixedThreadPool(2);
		hostLock = new ReentrantLock(); // create lock for game
		hostLock.newCondition();
		hostLock.newCondition();

		battleshipGameLauncherShell = new Shell();
		battleshipGameLauncherShell.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_FOREGROUND));
		battleshipGameLauncherShell.addControlListener(new ShellControlListener());
		battleshipGameLauncherShell.addDisposeListener(new ShellDisposeListener());
		battleshipGameLauncherShell.setImage(SWTResourceManager.getImage(MainWindow.class, "/images/16x16.png"));
		battleshipGameLauncherShell.setSize(634, 389);
		battleshipGameLauncherShell.setText("Battleship Game Launcher");
		GridLayout gl_battleshipGameLauncherShell = new GridLayout(1, false);
		gl_battleshipGameLauncherShell.marginHeight = 3;
		gl_battleshipGameLauncherShell.marginWidth = 3;
		battleshipGameLauncherShell.setLayout(gl_battleshipGameLauncherShell);

		Label label = new Label(battleshipGameLauncherShell, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.SHADOW_IN);
		label.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_FOREGROUND));
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));

		clientArea = new Composite(battleshipGameLauncherShell, SWT.NONE);
		clientArea.setBackground(SWTResourceManager.getColor(SWT.COLOR_TITLE_INACTIVE_FOREGROUND));
		GridData clientAreaLData = new GridData();
		clientAreaLData.heightHint = 322;
		clientAreaLData.verticalAlignment = GridData.FILL;
		clientAreaLData.horizontalAlignment = GridData.FILL;
		clientAreaLData.grabExcessHorizontalSpace = true;
		clientAreaLData.grabExcessVerticalSpace = true;
		clientArea.setLayoutData(clientAreaLData);
		{
			startserverbtn = new Button(clientArea, SWT.BORDER | SWT.FLAT | SWT.CENTER);
			startserverbtn.setFont(SWTResourceManager.getFont("@Adobe Gothic Std B", 9, SWT.BOLD));
			startserverbtn.setForeground(SWTResourceManager.getColor(SWT.COLOR_LIST_FOREGROUND));
			startserverbtn.setText("START SERVER");
			startserverbtn.setBounds(65, 0, 143, 30);
			startserverbtn.addSelectionListener(new SelectionAdapter() {

				public void widgetSelected(SelectionEvent evt) {
					startserverbtnWidgetSelected(evt);
				}
			});
		}
		{
			joinServerBtn = new Button(clientArea, SWT.BORDER | SWT.CENTER);
			joinServerBtn.setFont(SWTResourceManager.getFont("@Adobe Gothic Std B", 9, SWT.BOLD));
			joinServerBtn.setText("JOIN SERVER");
			joinServerBtn.setBounds(65, 72, 143, 30);
			joinServerBtn.addSelectionListener(new SelectionAdapter() {

				public void widgetSelected(SelectionEvent evt) {
					joinServerBtnWidgetSelected(evt);
				}
			});
		}
		{
			serverNameText = new Text(clientArea, SWT.CENTER);
			serverNameText.setFont(SWTResourceManager.getFont("@Adobe Gothic Std B", 9, SWT.ITALIC));
			serverNameText.setBackground(SWTResourceManager.getColor(SWT.COLOR_DARK_GRAY));
			serverNameText.setForeground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
			serverNameText.setText("Enter Host Name");
			serverNameText.setBounds(65, 36, 141, 30);
		}

		Label label_1 = new Label(battleshipGameLauncherShell, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.SHADOW_IN);
		label_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_FOREGROUND));
		label_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));

		Composite statusArea = new Composite(battleshipGameLauncherShell, SWT.NONE);
		statusArea.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_FOREGROUND));
		FillLayout fl_statusArea = new FillLayout(SWT.HORIZONTAL);
		fl_statusArea.marginWidth = 2;
		fl_statusArea.marginHeight = 2;
		statusArea.setLayout(fl_statusArea);
		GridData gd_statusArea = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_statusArea.widthHint = 125;
		statusArea.setLayoutData(gd_statusArea);

	}


	private void handleFileOpenRequest() {
		FileDialog dialog = new FileDialog(battleshipGameLauncherShell, SWT.OPEN);
		String filename = dialog.open();
		if (filename != null) {
			battleshipGameLauncherShell.setText(filename);
		}
	}


	private class OpenToolItemSelectionListener extends SelectionAdapter {

		@Override
		public void widgetSelected(SelectionEvent e) {
			handleFileOpenRequest();
		}
	}


	private class ShellDisposeListener implements DisposeListener {

		public void widgetDisposed(DisposeEvent arg0) {
			try {
				// Save app settings to file
				appSettings.store(new FileOutputStream("appsettings.ini"), "");
			} catch (Exception ex) {
			}
		}
	}


	private class ShellControlListener extends ControlAdapter {

		@Override
		public void controlMoved(ControlEvent e) {
			try {
				saveShellBounds();
			} catch (Exception ex) {
				setStatus(ex.getMessage());
			}
		}


		@Override
		public void controlResized(ControlEvent e) {
			try {
				saveShellBounds();
			} catch (Exception ex) {
				setStatus(ex.getMessage());
			}
		}
	}


	private void setStatus(String message) {
		//statusText.setText(message);
	}


	private void startserverbtnWidgetSelected(SelectionEvent evt) {
		System.out.println("startserverbtn.widgetSelected, event=" + evt);
		// TODO add your code for startserverbtn.widgetSelected
		if(!isServer){
		serverApplication = new GameServer();
		runServerClient.execute(serverApplication);
		isServer=true;
		////	Also join server
		try {
			clientApplication = new GameClient(InetAddress.getLocalHost().getHostName());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		clientApplication.battleshipBoard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		}
	}


	private void joinServerBtnWidgetSelected(SelectionEvent evt) {
		System.out.println("joinServerBtn.widgetSelected, event=" + evt);
		if ((!serverNameText.getText().equals("")) || !isServer) {
			String serverName = serverNameText.getText();
			clientApplication = new GameClient(serverName);
			clientApplication.battleshipBoard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		}

	}

}
